using System.Threading;
using System.Threading.Tasks;
using System.Utility.Logger;
using System.Utility.System;

namespace System.Utility
{
	public class Executer
	{
		public Executer()
		{
		}

		public static void TryRunByAsyn(Action fun, bool skipException = true)
		{
			TryRunSkipExceptoin(() => fun.BeginInvoke(null, null), skipException);
		}

		public static void TryRunByTask(Action fun, bool skipException = true)
		{
			Task.Factory.StartNew(() => TryRunSkipExceptoin(fun, skipException));
		}

		public static void TryRunByThread(Action fun, bool skipException = true)
		{
			Thread thread = new Thread(new ThreadStart(fun.Invoke))
			{
				IsBackground = true
			};
			if (!skipException)
			{
				thread.Start();
			}
			else
			{
				try
				{
					thread.Start();
				}
				catch
				{
				}
			}
		}

		public static void TryRunByThreadPool(Action fun, bool skipException = true)
		{
			ThreadPool.QueueUserWorkItem((object obj) => TryRunSkipExceptoin(fun, skipException));
		}

		public static void TryRunLogExceptioin(Action fun, string message = "")
		{
			try
			{
				fun();
			}
			catch (Exception exception1)
			{
				Exception exception = exception1;
				string.Format("{0}，{1}错误详情：{2}", message, Environment.NewLine, TypeExtension.AllMessage(exception));
				LogHelper.Error(message, exception);
			}
		}

		public static void TryRunSkipExceptoin(Action fun, bool skipException = true)
		{
			if (!skipException)
			{
				fun();
			}
			else
			{
				try
				{
					fun();
				}
				catch (Exception exception1)
				{
					Exception exception = exception1;
					LogHelper.Error(exception.Message, exception);
				}
			}
		}

		public static void TryRunThrowExceptioin(Action fun, string message = "")
		{
			try
			{
				fun();
			}
			catch (Exception exception1)
			{
				Exception exception = exception1;
				string str = string.Format("{0}，请尝试重新运行/重启程序，或者联系技术支持。{1}错误详情：{2}", message, Environment.NewLine, TypeExtension.AllMessage(exception));
				throw new ApplicationException(str, exception);
			}
		}
	}
}